from fastapi import APIRouter, FastAPI, Header, Query
from app.utils.logger import get_logger
from app.api.api_model import SuccessResponse

logger = get_logger()

router = APIRouter(
    prefix="/version",
    tags=["version V1"],
)
# 用路径做版本控制，获取版本信息
@router.get("/getversion", summary="获取版本信息")
async def get_version():
    return SuccessResponse(data={
        "desc":"用路径做版本控制",
        "version": "1.0.0"}
        )


# 用header做版本控制，可以作用于全局，使用中间件
# from fastapi import Request
# from typing import Callable

# class VersionMiddleware:
#     def __init__(self, app: FastAPI):
#         self.app = app

#     async def __call__(self, request: Request, call_next: Callable):
#         version = request.headers.get("API-Version", "v1")
#         # 根据版本号修改请求的路径
#         request.scope["path"] = f"/{version}{request.scope['path']}"
#         response = await call_next(request)
#         return response
    
# from app.middleware.version_middleware import VersionMiddleware

# app.add_middleware(VersionMiddleware)

# 单独接口处理
@router.get("/getversionbyheader", summary="通过header获取版本信息")
async def get_version(API_Version: str = Header(default="v1")):
    # version = request.headers.get("API-Version", "v1")
    if API_Version == "v1":
        return SuccessResponse(data={"desc":"用header做版本控制","version": "1.0.0"})
    elif API_Version == "v2":
        return SuccessResponse(data={"desc":"用header做版本控制","version": "2.0.0"})
    else:
        return SuccessResponse(data={"desc":"用header做版本控制","version": "3.0.0"})

# 参数化版本控制
@router.get("/getversionbyparam", summary="通过参数获取版本信息")
async def get_version(version: str = Query(default="v1")):
    if version == "v1":
        return SuccessResponse(data={"desc":"用参数做版本控制","version": "1.0.0"})
    elif version == "v2":
        return SuccessResponse(data={"desc":"用参数做版本控制","version": "2.0.0"})
    else:
        return SuccessResponse(data={"desc":"用参数做版本控制","version": "3.0.0"})

# 使用中间件做版本控制
# class VersionMiddleware(BaseHTTPMiddleware):
#     async def dispatch(self, request: Request, call_next: Callable):
#         accept = request.headers.get("Accept", "")
#         if "application/vnd.myapi.v2+json" in accept:
#             request.scope["app"] = api_auth_v2.router
#         else:
#             request.scope["app"] = api_auth_v1.router
#         response = await call_next(request)
#         return response
# 媒体类型版本化（Media Type Versioning）是一种通过修改 Content-Type 或 Accept 请求头中的媒体类型（MIME type）来管理 API 版本的方法。这种方法使得版本信息与资源路径分离，保持 URL 的简洁性，同时利用内容协商（Content Negotiation）实现不同版本的 API。
@router.get("/getversionbymime", summary="通过媒体类型版本化")
async def get_version(Accept: str = Header(default="application/vnd.myapi.v1+json")):
    if "application/vnd.myapi.v1+json" in Accept:
        return SuccessResponse(data={"desc":"通过媒体类型版本化","version": "1.0.0"})
    elif "application/vnd.myapi.v2+json" in Accept:
        return SuccessResponse(data={"desc":"通过媒体类型版本化","version": "2.0.0"})
    else:
        return SuccessResponse(data={"desc":"通过媒体类型版本化","version": "3.0.0"})
   